/*
 * Chapter.java
 *
 * Created on 18 de julio de 2007, 19:14
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package model;

import java.text.DateFormat;
import java.util.Date;
import java.util.Vector;
import org.w3c.dom.Document;

/**
 *
 * @author mariano
 */
public class Chapter extends xml.Xmlizable{
    
    private int order;
    private String name;
    private Index index;
    
    /** Creates a new instance of Chapter */
    public Chapter() {
        index = new Index();
    }
    
    public Chapter( int order, String name, Index index ) {
        this.order = order;
        this.name = name;
        this.index = index;
    }

    public int getOrder() {
        return order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Index getIndex() {
        return index;
    }

    public void setIndex(Index index) {
        this.index = index;
    }
    
    public xml.Coleccion toXmlColeccion()
    {
        xml.Coleccion col = new xml.Coleccion( "chapter" );
        col.addNodo( "chapter-order", "" + order );
        col.addNodo( "chapter-name", name );
        
        xml.Coleccion col1 = new xml.Coleccion( "chapter-index" );
        col1.addItem( index.toXmlColeccion() );
        
        col.addItem( col1 );
        
        return col;
    }
    
    public static Chapter fromXml( String str )
    {
        xml.Item col = xml.Item.fromXml( str );
        return parse( col );
    }
    
    public static Chapter fromXml( Document doc )
    {
        xml.Item col = xml.Item.fromXml( doc.getFirstChild() );
        return parse( col );
    }
    
    private static Chapter parse( xml.Item col )
    {
        if( !col.isColeccion() || col.getName() != "chapter" )
            return null;
        
        xml.Coleccion c = (xml.Coleccion)col;
        
        xml.Nodo nOrder = c.getNodo( 0, "chapter-order" );
        xml.Nodo nName = c.getNodo( 1, "chapter-name" );
        
        xml.Coleccion cChapterIndex = c.getColeccion( 2, "chapter-Index" );
        
        if( nOrder == null || nName == null || cChapterIndex == null )
            return null;
        
        xml.Coleccion cIndex = cChapterIndex.getColeccion( 0, "index" );
        Index index;
                
        if( cIndex == null )
        {
            index = new Index();
        }
        {
            index = Index.fromXml( cIndex.toString() );
        }
        
        int orderNumber = 0;
        
        try
        {
            orderNumber = Integer.parseInt( nOrder.getValue() );
        }
        catch( Exception ex ){}
        
        return new Chapter( orderNumber, nName.getValue(), index );
    }
    
}
